<template>
    <el-dialog v-model="dialogVisible" :title="title" width="30%" :before-close="handleClose">
        <el-form :model="form" label-width="120px">
            <el-form-item label="模板名称：">
                <el-input v-model="form.template_title" />
            </el-form-item>
            <el-form-item label="模板介绍：">
                <el-input v-model="form.description" type="textarea" />
            </el-form-item>
            <el-form-item label="模板图片：">
                <!-- 选择头像类型也是可以的 需求是需要有遮罩层里面显示删除按钮  所以使用的是照片墙，需要把'+'号框去掉 -->
                <el-upload v-model:file-list="fileList0" :action="domains + '/common/upload'"
                    :class="{ disabled: uploadDisabledOne }" list-type="picture-card"
                    :on-preview="handlePictureCardPreview0" :on-success="handleSuccess0" :on-change="handleChange0"
                    :on-remove="handleRemove0" :limit="1">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>

                <el-dialog v-model="dialogVisible0">
                    <img w-full :src="form.imageUrl" alt="Preview Image" />
                </el-dialog>
                <!-- <el-upload class="avatar-uploader" :action="domains + '/common/upload'" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload> -->

            </el-form-item>

            <el-form-item label="资源列表：">
                <div v-for="(item, indexes) in arr.addList " :key="item.idxxx" flex class="ziyuan">
                    <div>
                        <el-upload v-model:file-list="item.fileList" :action="domains + '/common/upload'"
                            :class="{ disabled: item.uploadDisabled }" list-type="picture-card" :limit="1"
                            :on-preview="handlePictureCardPreview.bind(null, { 'index': indexes, 'data': item })"
                            :on-remove="handleRemove.bind(null, { 'index': indexes, 'data': item })"
                            :on-success="handleSuccess.bind(null, { 'index': indexes, 'data': item })"
                            :on-change="handleChange.bind(null, { 'index': indexes, 'data': item })">
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </el-upload>
                        <el-dialog v-model="item.dialogVisible1">
                            <img w-full :src="item.album" alt="Preview Image" />
                        </el-dialog>
                    </div>
                    <div class="imgKuang">
                        <el-upload v-model:file-list="item.fileListZip" class="upload-demo"
                            :action="domains + '/common/upload'" multiple
                            :on-success="handleSuccess2.bind(null, { 'index': indexes, 'data': item })">
                            <el-button type="primary">本地上传</el-button>
                            <!-- <template #tip>
                                <div class="el-upload__tip">
                                    jpg/png files with a size less than 500KB.
                                </div>
                            </template> -->
                        </el-upload>
                    </div>
                    <div style="width:135px">
                        <el-radio-group v-model="item.way">
                            <el-radio :label="0">Android</el-radio>
                            <el-radio :label="1">ios</el-radio>
                        </el-radio-group>
                    </div>
                    <div>
                        <el-icon :size="26" @click="plusOne(indexes)">
                            <CirclePlus />
                        </el-icon>
                        <el-icon :size="26" @click="removeOne(indexes, item.idxxx, item)" v-if="arr.addList.length > 1">
                            <Remove />
                        </el-icon>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="音乐素材库：">

                <el-upload v-model:file-list="fileListMusic" class="upload-demo" ref="uploadRef"
                    :action="domains + '/common/upload'" multiple :limit="1" :on-exceed="handleExceed3"
                    :on-success="handleSuccess3">
                    <el-button type="primary">本地上传</el-button>

                </el-upload>
            </el-form-item>



            <el-form-item>
                <el-button type="primary" @click="onSubmit">新增</el-button>
                <el-button>重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>
  
<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
import domainsFuc from '../../../request/domains'
const domains = ref('')
import { Remove, CirclePlus } from '@element-plus/icons-vue'

const form = reactive({
    template_title: '',
    description: '',
    imageUrl: ''
})
// interface addListType {
//     fileList: never[];
//     fileListZip: never[];
//     album: string;
//     zip: string;
//     way: number;
//     dialogVisible1: boolean;
//     idxxx: number;
//     uploadDisabled: boolean;
// }
interface addlist2 {
    fileList: any;
    fileListZip: any;
    album: string;
    zip: string;
    way: number;
    dialogVisible1: boolean;
    idxxx: number;
    uploadDisabled: boolean;
}
interface addListType1 {
    addList: addlist2[]
}
let arr: addListType1 = reactive({
    addList: [{
        fileList: [],
        fileListZip: [],
        album: '',
        zip: '',
        way: 0,
        dialogVisible1: false,
        idxxx: 0,
        uploadDisabled: false

    }
    ]
}
)
// 上传模板图片列表
const fileList = ref<UploadUserFile[]>([])
const dialogImageUrl = ref('')
// const dialogVisible1 = ref(false)
const handleRemove = (obj, uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
    let index = obj.index
    // arr.addList[index].dialogVisible1 = false
    arr.addList[index].uploadDisabled = false
}

const handlePictureCardPreview: UploadProps['onPreview'] = (obj: any, response: any, uploadFile: any) => {
    let index = obj.index
    arr.addList[index].album = uploadFile.url!
    // dialogImageUrl.value = uploadFile.url!
    // arr.addList[index].dialogVisible1 = true
    if (arr.addList.length >= 1) {
        arr.addList[index].uploadDisabled = true
    }
}
const handleChange: UploadProps['onChange'] = (obj: any, response: any, uploadFile: any) => {

    let index = obj.index
    // arr.addList[index].dialogVisible1 = false
    if (arr.addList.length >= 1) {
        arr.addList[index].uploadDisabled = true
    }

}
const handleSuccess: UploadProps['onSuccess'] = (obj: any, response: any, uploadFile: any) => {
    console.log(obj, 'obj===');
    console.log(obj.index, 'obj===index');
    // response: any, uploadFile: UploadFile, uploadFiles: UploadFiles

    console.log(response.data.fullurl, 'response.data.fullurl====后端获取路径');
    let index = obj.index
    arr.addList[index].album = response.data.fullurl
    // arr.addList[index].dialogVisible1 = false
    if (arr.addList.length >= 1) {
        arr.addList[index].uploadDisabled = true
    }

    console.log(arr.addList, 'addList====1');
}
// 上传zip文件
const handleSuccess2: UploadProps['onSuccess'] = (obj: any, response: any, uploadFile: any) => {
    let index = obj.index
    arr.addList[index].zip = response.data.fullurl
    console.log(arr.addList, 'addList====2');
}
// 上传单个图片
const dialogVisible0 = ref(false)
const fileList0 = ref<UploadUserFile[]>([])
const handleSuccess0: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(response.data.fullurl, 'response====后端获取路径');
    console.log(uploadFile, 'uploadFile====');

    form.imageUrl = URL.createObjectURL(uploadFile.raw!)

    console.log(form.imageUrl, ' form.imageUrl====----');

}
const handleChange0: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
    uploadDisabledOne.value = true
}
const handleRemove0: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    uploadDisabledOne.value = false
}
const handlePictureCardPreview0: UploadProps['onPreview'] = (rawFile: any) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}
let uploadDisabledOne = ref(false)
const onSubmit = () => {
    console.log('submit!')
}
const dialogVisible = ref(false)

const plusOne = (indexes: number) => {
    arr.addList.push({
        fileList: [],
        fileListZip: [],
        album: '',
        zip: '',
        way: 0,
        dialogVisible1: false,
        idxxx: new Date().getTime(),
        uploadDisabled: false
    })

    console.log(arr.addList, 'addList-===4');
}
// 点击删除按钮后，数组发生了变化，但是页面不渲染。这是因为不能直接对reactive数组操作
const removeOne = (indexes: number, idxxx: number, item: any) => {
    console.log(indexes, idxxx, item.idxxx, '====000');
    // 方法一：
    // let newadd: addListType[] = []
    // arr.addList.forEach((e) => {
    //     if (e.idxxx != idxxx) {
    //         newadd.push(e)
    //     }
    // })
    // arr.addList = newadd
    // 方法二：
    arr.addList = [...arr.addList.filter(e => e.idxxx !== idxxx)]
    console.log(arr.addList, 'addList-===3');

    // addList = [...addList.filter(e => e.idxxx !== idxxx)]
}
const props = defineProps({
    title: {
        type: String,
        default: ''
    }
})
const showDio1 = (type: string, row: any) => {
    dialogVisible.value = true
    if (type == 'edit') {
        console.log(row, 'row')
        form.template_title = row.template_title
        form.description = row.description
        // 单个图片回写
        form.imageUrl = row.image
        fileList0.value = [{
            name: '图片',
            url: row.image,
        }]
        uploadDisabledOne.value = true
        // 循环图片回写
        if (row.zip_list.length > 0) {
            arr.addList = row.zip_list
            arr.addList.forEach((e: any, i: number) => {
                e.fileList = [{
                    name: '图片' + i,
                    url: e.album
                }]
                e.idxxx = new Date().getTime() + i
                e.uploadDisabled = true
                e.dialogVisible1 = false
                e.fileListZip = [{
                    name: '压缩包' + i,
                    url: e.zip
                }]
            })
        }
        if (row.from_bgm == 0) {
            fileListMusic.value = [{
                name: '音乐',
                url: row.bg_music
            }]
        }


    }
}
// 音乐素材库
const fileListMusic = ref<UploadUserFile[]>([])
const uploadRef = ref<any>()
const handleExceed3: UploadProps['onExceed'] = (files, uploadFiles) => {
    // 替换上次上传的值
    uploadRef.value.clearFiles()
    nextTick(() => {
        uploadRef.value.handleStart(files[0])
    })
}
const handleSuccess3: UploadProps['onSuccess'] = (response: any, uploadFile: any) => {
    console.log(response, 'response====');

}

const handleClose = (done: () => void) => {
    // 关闭弹窗清空数据
    arr.addList = [{
        fileList: [],
        fileListZip: [],
        album: '',
        zip: '',
        way: 0,
        dialogVisible1: false,
        idxxx: 0,
        uploadDisabled: false

    }
    ]
    done()

}
defineExpose({
    showDio1
})
onMounted(() => {
    domains.value = domainsFuc(process.env.NODE_ENV).domain
    // console.log(domains.value, 'domains===');

    // form.imageUrl = 'http://116.148.226.49:8001/uploads/20230919/40ead30cdb880ae1a8209f09cbc20d8d.jpg' //图片回写

})
</script>
<style scoped>
.dialog-footer button:first-child {
    margin-right: 10px;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<style lang="scss" scoped>
.ziyuan {
    background-color: #F3F3F3;
    padding: 10px;
    margin-bottom: 10px;

    .imgKuang {
        margin: 0 20px;
    }
}
</style>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

/* 去掉图片遮罩层中的放大按钮 */
.el-upload-list__item-preview {
    display: none !important;
}

.el-upload-list--picture-card .el-upload-list__item-actions span+span {
    margin-left: 0;
}

/* 去掉 + 框 */
.disabled .el-upload--picture-card {
    display: none;
}

/* el-upload 上传文件，去掉默认动画效果。 */
.el-upload-list__item {
    transition: none !important;
    -webkit-transition: nonne !important;
}

.el-upload-list__item-name {
    transition: none !important;
    -webkit-transition: nonne !important;
}

/* 上传框设置大小 */
.el-upload-list--picture-card .el-upload-list__item {
    width: 68px;
    height: 68px;
}

/* + 框 大小 */
.el-upload--picture-card {
    width: 68px;
    height: 68px;
}
</style>